//
//  PSCadastroViewController.m
//  psico
//
//  Created by wagner silva on 09/07/13.
//  Copyright (c) 2013 ws. All rights reserved.
//

#import "PSCadastroViewController.h"
#import "PSPerfilViewController.h"
#import "AESCrypt.h"

#define kPickerAnimationDuration 0.40

@interface PSCadastroViewController ()

@end

@implementation PSCadastroViewController

@synthesize checkButtonM;
@synthesize checkButtonF;
@synthesize txtEmail;
@synthesize txtSenha;
@synthesize txtConfSenha;
@synthesize btData;
@synthesize lblDtaNasc;
@synthesize pickerView;
@synthesize viewAbaixoDaData;
@synthesize toolBar;
@synthesize ocultarPickerData;

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
    
    checkedF = YES;
    checkedM = NO;
    bCal = NO;
    
    self.viewAbaixoDaData.alpha = 0;
    self.pickerView.alpha = 0;
    self.toolBar.alpha = 0;
    

}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


//Código de controle do CheckBox através de imagens com o campo marcado e desmarcado, masculino e feminino.

- (IBAction)checkButtonM:(id)sender
{ 
    if (!checkedM)
    {
        [checkButtonM setImage:[UIImage imageNamed:@"checkBoxMarked.png"] forState:UIControlStateNormal];
        
        [checkButtonF setImage:[UIImage imageNamed:@"checkBox.png"] forState:UIControlStateNormal];
        
        checkedM = YES;
        checkedF = NO;
    }
    
    else if (checkedM)
    {
        [checkButtonM setImage:[UIImage imageNamed:@"checkBox.png"] forState:UIControlStateNormal];
        [checkButtonF setImage:[UIImage imageNamed:@"checkBoxMarked.png"] forState:UIControlStateNormal];

        checkedM = NO;
        checkedF = YES;
    }

}

- (IBAction)checkButtonF:(id)sender
{
    if (!checkedF)
    {
        [checkButtonF setImage:[UIImage imageNamed:@"checkBoxMarked.png"] forState:UIControlStateNormal];
        [checkButtonM setImage:[UIImage imageNamed:@"checkBox.png"] forState:UIControlStateNormal];
        
        checkedF = YES;
        checkedM = NO;
    }
    
    else if (checkedF)
    {
        [checkButtonF setImage:[UIImage imageNamed:@"checkBox.png"] forState:UIControlStateNormal];
        [checkButtonM setImage:[UIImage imageNamed:@"checkBoxMarked.png"] forState:UIControlStateNormal];
        
        checkedF = NO;
        checkedM = YES;
    }
}


//Limpar campo ao clicar

- (IBAction)limparEmail:(id)sender
{
    txtEmail.text=@"";
}

- (IBAction)limparCampoSenha:(id)sender
{
    txtSenha.text = @"";
}

- (IBAction)limparCampoConfSenha:(id)sender
{
    txtConfSenha.text = @"";
}

// Controle de preenchimento obrigatório dos campos antes de enviá-lo para gravação

- (IBAction)onClickCadastro:(id)sender
{
    if ( [self validarEmail:[txtEmail text] ]  == 0)
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"alert" message:@"Formato de e-mail incorreto!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        
        [alert show];
       
    }
    
    if ([txtEmail.text isEqualToString:@""])
    {
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"alert" message:@"Preencha o seu e-mail " delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
        
        return;
    }
    
    else if ([txtSenha.text isEqualToString:@""] )
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"alert" message:@"Preencha o campo senha" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        
        [alert show];
        
        return;
    }
    else if ([txtConfSenha.text isEqualToString:@""] )
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"alert" message:@"Preencha a confirmacao de senha" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        
        [alert show];
        
        return;
    }
    
    if ([lblDtaNasc.text isEqualToString:@""] )
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"alert" message:@"Preencha a data" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        
        [alert show];
        
        return;
    }
  
    if (![txtSenha.text isEqualToString:txtConfSenha.text] )
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"alert" message:@"Formato de email invalido" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        
        [alert show];
        
        return;
    }
       
    NSString * sexo = nil;
    
    if (checkedM == YES)
    {
        sexo = @"M";
    }
    else
    {
        sexo = @"F";
    }
 
  
    NSString *data = [[NSString alloc] initWithFormat:@"%@", [self.pickerView date]];
    NSString * ano = [data substringWithRange:NSMakeRange(0,4)];
    NSString * mes = [data substringWithRange:NSMakeRange(5,2)];
    NSString * dia = [data substringWithRange:NSMakeRange(8,2)];
    
    NSString *dataFormatada = [[NSString alloc] initWithFormat:@"%@-%@-%@", ano,mes,dia];
    
    //Encriptando a senha
    
    NSString *senha = txtSenha.text;
    NSString *chave = txtEmail.text;
    
    NSString *senhaEncriptada = [AESCrypt encrypt:senha password:chave];
    
    // Função que controla a gravação em Banco de Dados utilizando o PHP;
    NSString *strURL = [NSString stringWithFormat:@"http://192.168.254.233:8080/pscadastrologin.php?email=%@&senha=%@&sexo=%@&dtnasc=%@",txtEmail.text.lowercaseString, senhaEncriptada, sexo, dataFormatada];
    
    // to execute php code
    NSData *dataURL = [NSData dataWithContentsOfURL:[NSURL URLWithString:strURL]];
    
    // to receive the returend value
    
   // NSString *strResult = [[NSString alloc] initWithData:dataURL encoding:NSUTF8StringEncoding];
    
    NSMutableString *strResult = [[NSMutableString alloc] initWithData:dataURL encoding:NSUTF8StringEncoding];
    
   
   
    if ([strResult isEqualToString:@"1"])
    {
        self.limparCamposCadastro;
       
        PSPerfilViewController *janela = [[PSPerfilViewController alloc] initWithNibName: @"PSPerfilViewController" bundle:nil];
        
        [self presentModalViewController:janela animated:true];
        
    }
    else
    {
        // invalid information
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"alert" message:@"Informação Inválida" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
        
        return;
    }
}

- (void) limparCamposCadastro
{
    txtEmail.text=@"";
    txtSenha.text = @"";
    txtConfSenha.text = @"";
}

- (IBAction)onClickData:(id)sender
{
    if (bCal == NO)
    {
        self.viewAbaixoDaData.alpha = 1;
        self.pickerView.alpha = 1;
        self.toolBar.alpha = 1;
        
        
        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationDuration:0.3];
        
        viewAbaixoDaData.frame = CGRectMake(0, 260, 320, 200);
        [UIView commitAnimations];
        
        bCal = YES;
    }
}


- (IBAction)alteraData:(id)sender
{
    NSString *data = [[NSString alloc] initWithFormat:@"%@", [self.pickerView date]];
    NSString * ano = [data substringWithRange:NSMakeRange(0,4)];
    NSString * mes = [data substringWithRange:NSMakeRange(5,2)];
    NSString * dia = [data substringWithRange:NSMakeRange(8,2)];
    NSString *dataFormatada = [[NSString alloc] initWithFormat:@"%@/%@/%@", dia,mes,ano];
    
    lblDtaNasc.text = dataFormatada;
}

//Controle de recuo do teclado para melhor visualizacão dos botões

- (IBAction)recuarTeclado:(id)sender
{   
    [sender resignFirstResponder];
}

- (IBAction)clicarNoFundo:(id)sender
{
    [txtEmail resignFirstResponder];
    [txtSenha resignFirstResponder];
    [txtConfSenha resignFirstResponder];
}

- (BOOL) validarEmail:(NSString *) candidate
{
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Aa-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
          
    return [emailTest evaluateWithObject:candidate];
}


- (IBAction)ocultarPickerData:(id)sender {
    
    bCal = YES;
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.3];
    [UIView commitAnimations];
    
    bCal = NO;
    
    viewAbaixoDaData.frame = CGRectMake(0, 460, 320, 261);
}
@end
